package com.zaofan.dao;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.Goods;
import com.zaofan.dao.base.DaoSupportImpl;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;

public class GoodsDao extends DaoSupportImpl<Goods> {

	public void setGoodsState(Goods goods) {
		try {
			String sql = "update " + Goods.class.getSimpleName().toLowerCase() + " set state = " + goods.getState()
					+ " where id = " + goods.getId();
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Integer addGoods(Goods goods) {
		Connection conn = C3p0DataSourceUtils.getConnection();
		int id = 0;
		try {
			String sql = SqlBuilderUtils.builderInsertSql(Goods.class, goods);
			System.err.println(sql);
			QueryRunner runner = new QueryRunner();
			runner.update(conn, sql);
			// 获取新增记录的自增主键
			try {
				Long t = (Long) runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<Long>());
				id = t.intValue();
			} catch (Exception e) {
				BigInteger t = (BigInteger) runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler<BigInteger>());
				id = t.intValue();
			}
		} catch (SQLException e) {
			id = 0;
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return id;
	}

	public void updateDateSellCount() {
		try {
			String sql = "update " + Goods.class.getSimpleName().toLowerCase() + " set dateCount = 0";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
